package com.example.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.blog.config.PublisherAware;
import com.example.blog.domain.*;
import com.example.blog.dto.operationalLogs.OperationLogsDto;
import com.example.blog.dto.picture.UpdateTriviaDto;
import com.example.blog.dto.trivia.AdminSelectTriviaDto;
import com.example.blog.dto.trivia.DelTriviaDto;
import com.example.blog.dto.trivia.TriviaInsertDto;
import com.example.blog.event.publisher.LoggingApplicationEvent;
import com.example.blog.note.LogInfo;
import com.example.blog.note.NoToken;
import com.example.blog.note.Permissions;
import com.example.blog.service.impl.TriviaServiceImpl;
import com.example.blog.service.impl.UuIdServiceImpl;
import com.example.blog.utils.IpUtil;
import com.example.blog.utils.UploadTheFile;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;

@RestController
@RequestMapping("/trivia")
@Transactional
@Validated
public class TriviaController extends BaseController {
    private final TriviaServiceImpl triviaService;
    private final UuIdServiceImpl uuIdService;
    private final PublisherAware loggingPublisherAware;

    @Autowired
    TriviaController(UuIdServiceImpl uuIdService, TriviaServiceImpl triviaService, PublisherAware loggingPublisherAware) {
        this.triviaService = triviaService;
        this.uuIdService = uuIdService;
        this.loggingPublisherAware = loggingPublisherAware;
    }

    @NoToken
    @LogInfo("获取所有琐事")
    @GetMapping("/getAll")
    public Response getAll() {
        return new Response(Response.SUCCEED_CODE, "获取琐事", triviaService.list());
    }

    @Permissions("/trivia/getAllAdmin")
    @LogInfo("Admin查询琐事")
    @PostMapping("/getAllAdmin")
    public Response getAllAdmin( @RequestBody AdminSelectTriviaDto querySearchDto) {
        IPage page = new Page(querySearchDto.getIndex(), querySearchDto.getPage());
        LambdaQueryWrapper<Trivia> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Objects.nonNull(querySearchDto.getDateTime()),Trivia::getTime,querySearchDto.getDateTime())
                .like(querySearchDto.getCondition() != null, Trivia::getContent, querySearchDto.getCondition())
                .orderByDesc(Trivia::getTime);
        return new Response(Response.SUCCEED_CODE, "获取所有琐事", triviaService.page(page, wrapper));
    }

    @Permissions("/trivia/insert")
    @LogInfo("Admin新增琐事")
    @PostMapping("/insert")
    public Response save(TriviaInsertDto triviaVo) {
        String img = null;
        OperationLogsDto logsVo = new OperationLogsDto(
                1, IpUtil.getIpAddress(getHttpInfo()), "新增管理员", getLogSign(), null);
        boolean insert = false;
        try {
            if (triviaVo.getFile() != null) {
                img = triviaService.uploadImg(new MultipartFile[]{triviaVo.getFile()});
            }
            Trivia trivia = new Trivia(img, triviaVo.getContent());
            insert = triviaService.save(trivia);
            logsVo.setCustomer("琐事id：".concat(String.valueOf(trivia.getId())));
            logsVo.setOutcome(1);
            loggingPublisherAware.publisher(new LoggingApplicationEvent(logsVo));
        } catch (Exception e) {
            logsVo.setOutcome(0);
            loggingPublisherAware.publisher(new LoggingApplicationEvent(logsVo));
            throw e;
        }
        return new Response(Response.SUCCEED_CODE, "新增成功", insert);
    }

    @Permissions("/trivia/update")
    @LogInfo("Admin更新琐事")
    @PostMapping("/update")
    public Response update(UpdateTriviaDto updateTriviaVo) {
        OperationLogsDto logsVo = new OperationLogsDto(
                0, IpUtil.getIpAddress(getHttpInfo()), "Admin更新琐事", getLogSign(), "琐事id：".concat(String.valueOf(updateTriviaVo.getId())));
        boolean update = false;
        try {
            Trivia trivia = new Trivia();
            String img;
            if (updateTriviaVo.getFile() != null) {
                img = triviaService.updatedImg(new MultipartFile[]{updateTriviaVo.getFile()}, updateTriviaVo.getTriviaImage());
                if (img == null) {
                    return new Response(Response.ERROR_CODE, "Admin更新琐事", null);
                }
                updateTriviaVo.setTriviaImage(img);
            }
            BeanUtils.copyProperties(updateTriviaVo, trivia);
            LambdaQueryWrapper<Trivia> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Trivia::getId, trivia.getId());
            update = triviaService.update(trivia, wrapper);
            logsVo.setOutcome(1);
            loggingPublisherAware.publisher(new LoggingApplicationEvent(logsVo));
        } catch (Exception e) {
            logsVo.setOutcome(0);
            loggingPublisherAware.publisher(new LoggingApplicationEvent(logsVo));
            throw e;
        }
        return new Response(Response.SUCCEED_CODE, "Admin更新琐事", update);
    }

    @Permissions("/trivia/del")
    @LogInfo("Admin删除琐事")
    @PostMapping("/del")
    public Response save(@RequestBody DelTriviaDto delTriviaVo) {
        OperationLogsDto logsVo = new OperationLogsDto(
                -1, IpUtil.getIpAddress(getHttpInfo()), "Admin删除琐事", getLogSign(), "琐事id：".concat(String.valueOf(delTriviaVo.getId())));
        boolean remove = false;
        try {

            UploadTheFile uploadTheFile = new UploadTheFile();
            //检查传来的文件名是否有‘/’有，则进行截取‘/’后的字符，再进行删除
            String[] fileName = UploadTheFile.intercept(new String[]{delTriviaVo.getDelImg()}, "/");
            // 删除oss存储的图片返回删除成功数量
            uploadTheFile.deleteFile(fileName);
            //删除数据库的uuid
            LambdaQueryWrapper<UuId> uuIdLambdaQueryWrapper = new LambdaQueryWrapper<>();
            uuIdService.remove(uuIdLambdaQueryWrapper.eq(UuId::getUuidValue, delTriviaVo.getDelImg()));
            LambdaQueryWrapper<Trivia> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Trivia::getId, delTriviaVo.getId());
            remove = triviaService.remove(wrapper);
            logsVo.setOutcome(1);
            loggingPublisherAware.publisher(new LoggingApplicationEvent(logsVo));
        } catch (Exception e) {
            logsVo.setOutcome(0);
            loggingPublisherAware.publisher(new LoggingApplicationEvent(logsVo));
            throw e;
        }
        return new Response(Response.SUCCEED_CODE, "Admin删除琐事", remove);
    }


}
